import {createReducer, on} from '@ngrx/store';
import {Step, setStep} from '../models/step.model';
import * as StepActions from '../actions/step.actions';

export interface stepState {
  loaded: boolean;
  loading: boolean;
  stepData: Step;
  current: number;
}

export const initialState: stepState = {
  loaded: false,
  loading: false,
  stepData: {
    step1: {
      name: '', isMale: '', isHandsome: ''
    },
    step2: {},
    step3: {},
  },
  current: 0
};

const currentMap = new Map([
  [0, 'step1'],
  [1, 'step2'],
  [2, 'step3'],
  [3, 'step4'],
])

export const stepReducer = createReducer(
  initialState,
  on(StepActions.setStepData, (state, {data}) => {
    const key = currentMap.get(state.current) as keyof Step
    const stepData = {
      ...state.stepData,
      [key]: data
    }
    return {...state, stepData}
  }),
  on(StepActions.getStepData, (state) => (
    {...state}
  )),
  on(StepActions.preCurrent, (state) => {
    const getStepData = (cur: number): any => {
      const current = cur - 1;
      if (current === 0) return {...state, current};
      const key = currentMap.get(current) as keyof Step;
      if (Object.keys(state.stepData[key]).length === 0) {
        return getStepData(current);
      }
      return {...state, current};
    };
    const cur = state.current
    return getStepData(cur);
  }),
  on(StepActions.nextCurrent, (state) => {
    if (state.current + 1 >= 4) return {...state}
    const current = state.current + 1;
    return {...state, current}
  }),
);
